package com.xiaoming.api.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoming.api.IUserService;
import com.xiaoming.base.BaseApiService;
import com.xiaoming.base.ResponseBase;
import com.xiaoming.constants.Constants;
import com.xiaoming.entity.User;
import com.xiaoming.api.mapper.UserMapper;
import com.xiaoming.stream.RegisterEmailProducer;
import com.xiaoming.utils.MD5Util;
import com.xiaoming.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * <p>
 *   服务实现类
 * </p>
 *
 * @author xiaoming
 * @since 2020-03-10
 */
@RestController
@Slf4j
public class UserServiceImpl extends BaseApiService implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RegisterEmailProducer registerEmailProducer;



    @Override
    public ResponseBase registerUser(@RequestBody User user) {
        String username = user.getUsername();
        if (StringUtils.isEmpty(username)) {
            return setResultError("用户名称不能为空!");
        }
        String password = user.getPassword();
        if (StringUtils.isEmpty(password)) {
            return setResultError("密码不能为空!");
        }
        String newPassWord= MD5Util.md5(password);
        user.setPassword(newPassWord);
        String email = user.getEmail();
        if (StringUtils.isEmpty(email)) {
            return setResultError("邮箱不能为空!");
        }
        Integer insertUser = userMapper.insert(user);
        if (insertUser <= 0) {
            return setResultError("注册失败!");
        }
        String message = message(email);
        registerEmailProducer.sendMsg(message);
        return setResultSuccess();
    }

    private String message(String email){
        JSONObject root = new JSONObject();
        JSONObject header = new JSONObject();
        header.put("interfaceType", Constants.SMS_MAIL);
        JSONObject content = new JSONObject();
        content.put("email", email);
        root.put("header", header);
        root.put("content", content);
        return root.toJSONString();

    }

    @Override
    public ResponseBase findUserByOpenId(String openId) {
        if (StringUtils.isEmpty(openId)) {
            return setResultError("openId不能为空!");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        HashMap<String, Object> map = new HashMap<>(2);
        map.put("openId",openId);
        User userEntity  = userMapper.selectOne(queryWrapper.allEq(map));
        if (userEntity == null) {
            return setResultErrorCode(Constants.HTTP_RES_CODE_201, "用户未授权QQ登录.");
        }
        return setLogin(userEntity);
    }

    @Override
    public ResponseBase qqLoginOpenId(User user) {
        // 1.验证参数
        String username = user.getUsername();
        if (StringUtils.isEmpty(username)) {
            return setResultError("用戶名称不能为空!");
        }
        String password = user.getPassword();
        if (StringUtils.isEmpty(password)) {
            return setResultError("密码不能为空!");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        HashMap<String, Object> map = new HashMap<>(2);
        map.put("username",username);
        map.put("password",MD5Util.md5(password));
        User userEntity  = userMapper.selectOne(queryWrapper.allEq(map));
        if (userEntity == null) {
            return setResultError("账号或者密码不能正确");
        }
        // 3. 关联userid
        String openid = user.getOpenid();
        userEntity.setOpenid(openid);
        userMapper.updateById(userEntity);
        return setLogin(userEntity);
    }

    @Override
    public ResponseBase findUserByToken(String token) {
        if (StringUtils.isEmpty(token)) {
            return setResultError("token不能为空.");
        }

        String userId = (String) baseRedisService.getString(token);
        if(StringUtils.isEmpty(userId)){
            return setResultError("未查询到用户信息");
        }
        Long userIdL=Long.parseLong(userId);
        User user = userMapper.selectById(userIdL);
        if (user == null) {
            return setResultError("未查询到用户信息");
        }
        user.setPassword(null);
        user.setToken(null);
        return setResultSuccess(user);
    }

    @Override
    public ResponseBase login(@RequestBody User user) {
        String username = user.getUsername();
        if (StringUtils.isEmpty(username)) {
            return setResultError("用户名称不能为空!");
        }
        String password = user.getPassword();
        if (StringUtils.isEmpty(password)) {
            return setResultError("密码不能为空!");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        HashMap<String, Object> map = new HashMap<>(2);
        map.put("username",username);
        map.put("password",MD5Util.md5(password));
        User userEntity  = userMapper.selectOne(queryWrapper.allEq(map));
        if (userEntity == null) {
            return setResultError("账号或密码错误!");
        }
       return setLogin(userEntity);
    }

    private ResponseBase setLogin(User user){
        String token = user.getToken();
        JSONObject jsonObject = new JSONObject();
        if (StringUtils.isNotEmpty(token)){
            jsonObject.put(Constants.MEMBER_TOKEN, token);
            baseRedisService.setString(token, user.getId()+"", null);
            return setResultSuccess(jsonObject);
        }
        // 生成token
        token = TokenUtils.getToken();
        baseRedisService.setString(token, user.getId()+"", null);
        user.setToken(token);
        userMapper.updateById(user);
        jsonObject.put(Constants.MEMBER_TOKEN, token);
        return setResultSuccess(jsonObject);
    }

    @Override
    public ResponseBase findUserById(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return setResultError("未查找到用户信息.");
        }
        return setResultSuccess(user);
    }

    @Override
    public ResponseBase updateUser(@RequestBody User user) {
        User selectById = userMapper.selectById(user.getId());
        if (selectById == null){
            return setResultError("用户不存在!");
        }
        user.setVersion(selectById.getVersion());
        int i = userMapper.update(user, null);
        if (i <= 0) {
            return setResultError("更新失败!");
        }
        return setResultSuccess();
    }
}
